﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Web.Script.Serialization;
using System.Data;
using System.Collections;
using System.Reflection;

namespace Common
{
    public class JsonHelper
    {
        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T">(泛型)</typeparam>
        /// <param name="obj">待转换的类型</param>
        /// <returns></returns>
        public static string GetJson<T>(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);

                string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson;
            }
        }

        /// <summary>
        /// 获取Json的Model
        /// </summary>
        /// <typeparam name="T">(泛型)</typeparam>
        /// <param name="szJson">待转换的json字符串</param>
        /// <returns></returns>
        public static T ParseFromJson<T>(string szJson)
        {
            if (string.IsNullOrEmpty(szJson))
            {
                return default(T);
            }
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }

        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <param name="obj">待转换的类型</param>
        /// <returns></returns>
        public static string Serialize(object obj)
        {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            return Serializer.Serialize(obj);
        }

        /// <summary>
        /// 获取Json的Model
        /// </summary>
        /// <typeparam name="T">(泛型)</typeparam>
        /// <param name="szJson">待转换的json字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string szJson)
        {
            if (string.IsNullOrEmpty(szJson))
            {
                return default(T);
            }
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            T obj = Serializer.Deserialize<T>(szJson);
            return obj;
        }
        /// <summary>
        /// 根据DataTable返回json字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableGetJson(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();

            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append("\"T_blog\":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }

                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 对象转换为Json字符串
        /// </summary>
        public static string ToJson(object model)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("{");
                PropertyInfo[] propertyInfo = model.GetType().GetProperties();
                for (int i = 0; i < propertyInfo.Length; i++)
                {
                    object objectval = propertyInfo[i].GetGetMethod().Invoke(model, null);
                    if (objectval == null) continue;

                    StringBuilder val = new StringBuilder();

                    if (objectval is DateTime || objectval is Guid || objectval is TimeSpan)
                        val.Append("\"" + objectval.ToString() + "\"");
                    else if (objectval is string)
                        val.Append("\"" + objectval.ToString() + "\"");
                    else if (objectval is IEnumerable)
                        val.Append(ToJson((IEnumerable)objectval));
                    else
                        val.Append("\"" + objectval.ToString() + "\"");

                    sb.Append("\"" + propertyInfo[i].Name + "\":" + val + ",");
                }
                return sb.ToString().TrimEnd(',') + "}";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 对象集合转换Json
        /// </summary>
        public static string ToJson(IEnumerable array)
        {
            string s = "[";
            foreach (object item in array)
            {
                s += ToJson(item) + ",";
            }
            s.Remove(s.Length - 1, s.Length);
            return s + "]";
        }


        /// <summary>
        /// 普通集合转换Json
        /// </summary>
        public static string ToArrayJson(IEnumerable array)
        {
            string s = "[";
            foreach (object item in array)
            {
                s = ToJson(item.ToString()) + ",";
            }
            s.Remove(s.Length - 1, s.Length);
            return s + "]";
        }


        /// <summary>
        /// Datatable转换为Json
        /// </summary>
        public static string ToJson(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                sb.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    sb.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);

                    if (j < dt.Columns.Count - 1)
                        sb.Append(strValue + ",");
                    else
                        sb.Append(strValue);
                }
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("]");


            return sb.ToString();
        }


        /// <summary>
        /// DataTable转成Json
        /// </summary>
        public static string ToJson(DataTable dt, string tblName)
        {
            StringBuilder sb = new StringBuilder();
            if (string.IsNullOrEmpty(tblName)) tblName = dt.TableName;


            sb.Append("{\"" + tblName + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sb.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        sb.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));

                        if (j < dt.Columns.Count - 1) sb.Append(",");
                    }
                    sb.Append("}");


                    if (i < dt.Rows.Count - 1) sb.Append(",");
                }
            }
            sb.Append("]}");


            return sb.ToString();
        }


        /// <summary>
        /// DataReader转换为Json
        /// </summary>
        public static string ToJson(IDataReader dr)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");


            while (dr.Read())
            {
                sb.Append("{");
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    Type type = dr.GetFieldType(i);
                    string strKey = dr.GetName(i);
                    string strValue = dr[i].ToString();


                    sb.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);


                    if (i < dr.FieldCount - 1)
                        sb.Append(strValue + ",");
                    else
                        sb.Append(strValue);
                }
                sb.Append("},");
            }
            dr.Close();


            sb.Remove(sb.Length - 1, 1);
            sb.Append("]");


            if (sb.Length == 1) return "[]";
            return sb.ToString();
        }


        /// <summary>
        /// DataSet转换为Json
        /// </summary>
        public static string ToJson(DataSet ds)
        {
            string sb = "{";
            foreach (DataTable table in ds.Tables)
            {
                sb += "\"" + table.TableName + "\":" + ToJson(table) + ",";
            }
            sb = sb.TrimEnd(',');
            return sb + "}";
        }


        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"': sb.Append("\\\""); break;
                    case '\\': sb.Append("\\\\"); break;
                    case '/': sb.Append("\\/"); break;
                    case '\b': sb.Append("\\b"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    default: sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        private static string StringFormat(string str, Type t)
        {
            if (t != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            else if (t == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (t == typeof(DateTime))
            {
                str = "\"" + str.Split(' ')[0] + "\"";
            }
            else if (t == typeof(bool))
            {
                str = str.ToLower();
            }


            return str;
        }

    }
}
